package exttable.questionnaire;

import dbutils.DbUtils;
import exttable.dbclasses.Answer;
import exttable.dbclasses.Probationer;
import exttable.dbclasses.Question;
import exttable.formgenerator.ListenerFactory;
import exttable.formgenerator.SelectPhaseAndProbationerFormForQuestionnaire;
import utils.Localisation;

import javax.swing.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: alex
 * Date: 30.10.2010
 * Time: 19:48:40
 * To change this template use File | Settings | File Templates.
 */
public class QuestionnaireService {
    private Connection conn;
    private JFrame frame;
    private JPanel questionPanel;
    private JScrollPane scrollPanel;
    private JButton saveButton;
    private Probationer probationer;
    private int visitId;
    private Map<Integer, Integer> mapQuestionIdAnswerId;

    public QuestionnaireService() throws Exception {
        conn = DbUtils.getDBConnectionGeneral();
        initQuestionList();
    }

    public QuestionnaireService(Probationer p, int visitId) throws Exception {
        this.probationer = p;
        this.visitId = visitId;
        this.mapQuestionIdAnswerId=getMapQuestionIdPoints(probationer.getProbationer_id(), visitId);
        conn = DbUtils.getDBConnectionGeneral();
        initQuestionList();
    }

    private void initQuestionList() throws Exception {
        Connection conn = null;
        PreparedStatement ps;
        try {
            conn = DbUtils.getDBConnectionGeneral();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {

            List<Question> questions = new ArrayList<Question>(11);


            ps = conn.prepareStatement("SELECT general_quest_id, name_ru FROM dic_general_questions");
            ResultSet rs = ps.executeQuery();
            int i = 0;
            while (rs.next()) {
                i++;
                Question q = new Question();
                q.setQuestionId(rs.getInt("general_quest_id"));
                q.setQuestionLabel(brakeLines(String.valueOf(i) + " " + rs.getString("name_ru")));
                ps = conn.prepareStatement("select question_id, general_quest_id, name_ru, question_symbol from questions where general_quest_id = ?");
                ps.setInt(1, q.getQuestionId());
                ResultSet rs2 = ps.executeQuery();
                List<Question> subQuestions = new ArrayList<Question>();
                while (rs2.next()) {
                    if (rs2.getString("name_ru") != null) {
                        Question sq = new Question();
                        sq.setQuestionId(rs2.getInt("question_id"));
                        sq.setQuestionLabel(brakeLines(rs2.getString("question_symbol") + "   " + rs2.getString("name_ru")));
                        sq.setAnswerBox(getAnswerBox(sq.getQuestionId(), ps, false));
                        if(mapQuestionIdAnswerId.size()>0){
                        sq.getAnswerBox().setSelectedIndex(mapQuestionIdAnswerId.get(sq.getQuestionId())-1);
                        }
                        subQuestions.add(sq);
                    }
                }
                q.setSubQuestions(subQuestions);
                if (q.getSubQuestions().size() == 0) {
                    q.setAnswerBox(getAnswerBox(q.getQuestionId(), ps, true));
                    if(mapQuestionIdAnswerId.size()>0){
                      q.getAnswerBox().setSelectedIndex(mapQuestionIdAnswerId.get(q.getQuestionId())-1);
                    }
                }
                questions.add(q);
            }
            generateUI(questions);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private JComboBox getAnswerBox(int questionID, PreparedStatement ps, boolean isGeneralQuestion) throws Exception {

        JComboBox toReturn = new JComboBox();
        try {
            if (isGeneralQuestion) {
                ps = conn.prepareStatement("select answer_id, question_id, points, name_ru from answers\n" +
                        "where answers.question_id IN((SELECT question_id from questions where general_quest_id=?))");
            } else {
                ps = conn.prepareStatement("select answer_id, question_id, points, name_ru from answers where question_id = ?");
            }
            ps.setInt(1, questionID);
            ResultSet rs = ps.executeQuery();
            List<Answer> answers = new ArrayList<Answer>();
            while (rs.next()) {
                Answer a = new Answer();
                a.setAnswerId(rs.getInt("answer_id"));
                a.setQuestionId(rs.getInt("question_id"));
                a.setPoints(rs.getInt("points"));
                a.setAnswerLabel(brakeLines(rs.getString("name_ru")));
                answers.add(a);
            }
            ComboBoxModel cbm = new DefaultComboBoxModel(answers.toArray());
            toReturn.setModel(cbm);
            return toReturn;

        } catch (SQLException e) {
            throw new Exception("erro;");
        }
    }

    private void generateUI(List<Question> questions) {
        frame = new JFrame(Localisation.getMessage("menu.questionnaire") + " " + DbUtils.ModeOfOperation);
        frame.setName(Localisation.getMessage("menu.questionnaire") + " " + DbUtils.ModeOfOperation);
        questionPanel = new JPanel();
        scrollPanel = new JScrollPane();
        for (Question q : questions) {
            questionPanel.add(q.getQuestionLabel());
            if (q.getAnswerBox() != null) {
                questionPanel.add(q.getAnswerBox());
            }
            if (q.getSubQuestions().size() > 0) {
                for (Question sq : q.getSubQuestions()) {
                    questionPanel.add(sq.getQuestionLabel());
                    questionPanel.add(sq.getAnswerBox());
                }
            }
        }
        saveButton = new JButton(Localisation.getMessage("form.saveresult"));
        saveButton.addActionListener(ListenerFactory.saveAnswers(questions, probationer, visitId, SelectPhaseAndProbationerFormForQuestionnaire.getOperation()));
        questionPanel.setPreferredSize(new Dimension(700, 1500));
        scrollPanel.setViewportView(questionPanel);
        frame.add(scrollPanel);
        frame.add(saveButton, BorderLayout.SOUTH);
        organiseLayout(questions);
        frame.setSize(new Dimension(1100, 600));
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    }

    private void organiseLayout(List<Question> questions) {
        SpringLayout layout = new SpringLayout();
        questionPanel.setLayout(layout);
        int i = 5;
        for (Question q : questions) {
            layout.putConstraint(SpringLayout.WEST, q.getQuestionLabel(), 5, SpringLayout.WEST, questionPanel);
            layout.putConstraint(SpringLayout.NORTH, q.getQuestionLabel(), i, SpringLayout.NORTH, questionPanel);

            if (q.getAnswerBox() != null) {
                layout.putConstraint(SpringLayout.WEST, q.getAnswerBox(), 750, SpringLayout.WEST, questionPanel);
                layout.putConstraint(SpringLayout.NORTH, q.getAnswerBox(), i, SpringLayout.NORTH, questionPanel);
            }

            i = i + 20 + q.getQuestionLabel().getHeight();

            if (q.getSubQuestions().size() > 0) {
                for (Question sq : q.getSubQuestions()) {
                    layout.putConstraint(SpringLayout.WEST, sq.getQuestionLabel(), 25, SpringLayout.WEST, questionPanel);
                    layout.putConstraint(SpringLayout.NORTH, sq.getQuestionLabel(), i, SpringLayout.NORTH, questionPanel);

                    layout.putConstraint(SpringLayout.WEST, sq.getAnswerBox(), 750, SpringLayout.WEST, questionPanel);
                    layout.putConstraint(SpringLayout.NORTH, sq.getAnswerBox(), i, SpringLayout.NORTH, questionPanel);
                    i += 30;
                }
            }
        }

    }

    private JLabel brakeLines(String line) {
        JLabel toReturn = new JLabel();
        if (line.length() > 105) {
            String a = line.substring(105);
            String b = line.substring(0, 105);
            toReturn.setText("<html>" + b + "<P>" + a + "</html>");
            toReturn.setSize(900, 30);
            return toReturn;

        } else {
            toReturn.setText(line);
            toReturn.setSize(900, 15);
            return toReturn;
        }
    }

    private Map<Integer, Integer> getMapQuestionIdPoints(int probationerId, int visitId) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        String query = "SELECT" +
                " questions.question_id," +
                " result_answers.points" +
                " FROM" +
                " result_answers" +
                " INNER JOIN answers ON (result_answers.answer_id = answers.answer_id)" +
                " INNER JOIN questions ON (answers.question_id = questions.question_id)" +
                " WHERE" +
                " probationer_id=?" +
                " and vizit_id=?";
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            conn=DbUtils.getDBConnectionGeneral();
            ps = conn.prepareStatement(query);
            ps.setInt(1, probationerId);
            ps.setInt(2, visitId);
            rs=ps.executeQuery();
            while(rs.next()){
                map.put(rs.getInt("question_id"), rs.getInt("points"));
            }
            rs.close();
            ps.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

//    public static void main(String[] args) throws Exception {
//        new QuestionnaireService();
//    }
}
